package com.qrpay.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.*;

public final class ObjectUtils {

    private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class);

    private ObjectUtils() {
    }

    public static Map<String, Field> getAllFields(Class clazz) {
        final Map<String, Field> fieldMap = new LinkedHashMap<>();
        iterateAllFields(clazz, f -> fieldMap.put(f.getName(), f));
        return fieldMap;
    }

    public static Map<String, Field> getDeclaredFields(Class clazz) {
        final Map<String, Field> fieldMap = new LinkedHashMap<>();
        iterateDeclaredFields(clazz, f -> fieldMap.put(f.getName(), f));
        return fieldMap;
    }

    public static void iterateAllFields(Class clazz, FiledFilter filter) {
        if (null == clazz || null == filter) {
            return;
        }

        do {
            iterateDeclaredFields(clazz, filter);
        } while (null != clazz.getSuperclass()
                && Object.class != (clazz = clazz.getSuperclass()));
    }

    public static void iterateDeclaredFields(Class clazz, FiledFilter filter) {
        for (Field f : clazz.getDeclaredFields()) {
            filter.doItem(f);
        }
    }

    public interface FiledFilter<T extends Collection> {
        void doItem(Field field);
    }
}
